//
//  THNewFeatureView.swift
//  Practise
//
//  Created by flower on 2017/9/7.
//  Copyright © 2017年 lalala. All rights reserved.
//

import UIKit

/// 新特性视图
class THNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterButton: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!
    
    /// 进入微博
    @IBAction func enterStatus() {
         removeFromSuperview()
        
    }
    
    //使用 Xib 加载欢迎视图
    class func newFeatureView() -> THNewFeatureView {
        let nib = UINib(nibName: "THNewFeatureView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! THNewFeatureView
        
        // 从 XIB 中加载视图  默认是 600 * 600
        v.frame = UIScreen.main.bounds
        
        return v
        
    }
    
    override func awakeFromNib() {
        
        // 如果使用是自动布局设置界面, 从 XIB 加载默认是 600 * 600 大小
        // 添加 4 个图像视图
        let count = 4
        let rect = UIScreen.main.bounds
        
        for i in 0..<count {
            
            let imageName = "new_feature_\(i + 1)"
            let iv = UIImageView(image:UIImage(named: imageName))
            
            // 设置大小
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            scrollView.addSubview(iv)
        }
        
        // 指定 scrollView 属性
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.delegate = self
        
        //隐藏按钮
        enterButton.isHidden = true
    }

    
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        
//        backgroundColor = UIColor.orange
//    }
//    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }

}

extension THNewFeatureView: UIScrollViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        // 1. 滚动到最后一屏, 让视图删除
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 2. 判断是否是最后一页
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }
        // 3. 如果是倒数第二页, 显示按钮
        enterButton.isHidden = (page != scrollView.subviews.count - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 1. 一旦滚动隐藏按钮
        enterButton.isHidden = true
        // 2. 计算当前偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        // 3. 设置分页控件
        pageControl.currentPage = page
        // 4. 分页控件隐藏
        pageControl.isHidden = (page == scrollView.subviews.count)
        
    }
}
